﻿//======================================================================
//
//        Copyright (C) 2007-2008 三月软件工作室    
//        All rights reserved
//
//        filename :GetTablesByConnection
//        description :
//
//        created by 侯垒 at  2009-11-14 10:43:23
//        http://houleixx.cnblogs.com
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;

namespace Entity.Core
{
    /// <summary>
    /// 得到数据库下所有表名
    /// </summary>
    public class GetTablesByConnection
    {
        string connection = string.Empty;
        string provider = string.Empty;
        string dataBaseName = string.Empty;
        DbProviderFactory factory;
        /// <summary>
        /// 构造函数；
        /// </summary>
        /// <param name="connection">数据库链接字符串</param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public GetTablesByConnection(string connection, string dataBaseName, string provider)
        {
            this.connection = connection;
            this.provider = provider;
            this.dataBaseName = dataBaseName;
            factory = DbProviderFactories.GetFactory(provider);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="model">连接实体</param>
        public GetTablesByConnection(ConnectionModel model)
        {
            this.connection = model.ConnectionString;
            this.provider = model.Provider;
            this.dataBaseName = model.DataBaseName;
            factory = DbProviderFactories.GetFactory(provider);
        }

        /// <summary>
        /// 根据数据库链接得到所有表名
        /// </summary>
        /// <returns></returns>
        public DataTable GetTables()
        {
            using (DbConnection conn = factory.CreateConnection())
            {
                conn.ConnectionString = connection;
                conn.Open();
                DataTable table = conn.GetSchema("tables");
                return table;
            }
        }

        /// <summary>
        /// 连接字符串的数据库名。
        /// </summary>
        public string DataBaseName
        {
            get
            {
                return dataBaseName;
            }
        }
    }
}
